package com.rzico.sbl.ui.report.manager

import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportThird2Binding
import com.rzico.sbl.model.ManagerSaleData
import com.rzico.sbl.model.SaleChartData
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.ReportThirdViewModel
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.showListDialog

class ReportThird2Activity : BaseActivity(R.layout.activity_report_third_2) {

    private val mBinding by lazy { ActivityReportThird2Binding.bind(getRootView()) }

    private val mAllList = arrayListOf<ManagerSaleData>()
    private val mOneList = arrayListOf<SaleChartData>()
    private val mTwoList = arrayListOf<SaleChartData>()
    private val mThreeList = arrayListOf<SaleChartData>()

    private var mStationId = ""
    private var mProductId = ""
    private var mBeginDate = getBeforeDate(6)
    private var mEndDate = getTodayDate()

    override fun getViewModel() = get<ReportThirdViewModel>()

    override fun initData() {
        initTitle("销量统计")

        initLayout()

        getData()
    }

    private fun initLayout() {
        mBinding.also {
            it.thirdSale1.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    xTextSize = 8f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mOneList.indices) ""
                    else mOneList[value.toInt()].stationName
                }
            }

            it.thirdSale2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    xTextSize = 8f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mTwoList.indices) ""
                    else mTwoList[value.toInt()].productName
                }
            }

            it.thirdSale3.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mThreeList.indices) ""
                    else mThreeList[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.thirdSaleTime.addTimeListener { start, end, _ ->
                mBeginDate = start
                mEndDate = end
                mStationId = ""
                mProductId = ""

                getViewModel().cancelRequest()
                getData()
            }
        }
    }

    override fun initListener() {
        mBinding.apply {
            thirdSaleSwitch1.oneClick {
                mOneList.notEmpty {
                    val stations = arrayListOf("全部水站")
                    mOneList.mapTo(stations) { it.stationName }

                    showListDialog(
                        title = "切换水站",
                        items = stations,
                        listener = { index, _ ->
                            if (index == 0) {
                                mStationId = ""
                                mProductId = ""
                            } else {
                                mProductId = ""
                                mStationId = mOneList[index - 1].stationId
                            }

                            setSaleSecondData(mStationId)
                            setSaleThirdData(mStationId, mProductId)
                        }
                    )
                }
            }

            thirdSaleSwitch2.oneClick {
                mTwoList.notEmpty {
                    val products = arrayListOf("全部商品")
                    mTwoList.mapTo(products) { it.productName }

                    showListDialog(
                        title = "切换商品",
                        items = products,
                        listener = { index, _ ->
                            mProductId =
                                if (index == 0) ""
                                else mTwoList[index - 1].productId

                            setSaleSecondData(mStationId)
                            setSaleThirdData(mStationId, mProductId)
                        }
                    )
                }
            }
        }
    }

    /**
     * 设置所有水站销量柱状图数据
     */
    private fun setSaleFirstData() {
        mAllList.sumOf {
            it.quantity.intValue
        }.apply {
            mBinding
                .thirdSaleTotal
                .text = if (this > 0) " (总: ${this})" else ""
        }

        mBinding
            .thirdSale1
            .apply {
                if (mOneList.isEmpty()) {
                    clear()
                    mBinding.thirdSaleTitle1.text = "暂无水站销量信息"
                } else {
                    setSingleData(
                        entries = mOneList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.quantity)
                        },
                        colorList = getViewModel().brandColor(),
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置指定水站的商品销量柱状图数据
     */
    private fun setSaleSecondData(staionId: String = "") {
        mTwoList.clear()
        mAllList
            .filter { staionId.isEmpty() || it.eid == staionId }
            .groupBy { it.pid }
            .mapTo(mTwoList) { entry ->
                SaleChartData(
                    stationId = staionId,
                    productId = entry.key,
                    productName = entry.value[0].pname,
                    quantity = entry.value.sumOf { it.quantity.intValue }.toFloat()
                )
            }

        mBinding
            .thirdSale2
            .apply {
                if (mTwoList.isEmpty()) {
                    clear()
                    mBinding.thirdSaleTitle2.text = "暂无商品销量信息"
                } else {
                    mBinding
                        .thirdSaleTitle1
                        .text =
                        if (staionId.isEmpty()) "全部水站"
                        else {
                            val item = mOneList.first { it.stationId == staionId }
                            "${item.stationName}（销量：${item.quantity.toInt()}）"
                        }

                    setSingleData(
                        entries = mTwoList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.quantity)
                        },
                        colorList = when {
                            staionId.isEmpty() -> getViewModel().brandColor()
                            else -> listOf(
                                getViewModel()
                                    .brandColor()[
                                        mOneList.indexOfFirst { it.stationId == staionId } % 24
                                ]
                            )
                        },
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置指定水站的指定商品时间范围内的销量柱状图数据
     */
    private fun setSaleThirdData(
        staionId: String = "",
        productId: String = ""
    ) {
        mThreeList.clear()
        mAllList
            .filter { staionId.isEmpty() || it.eid == staionId }
            .filter { productId.isEmpty() || it.pid == productId }
            .groupBy { it.date }
            .mapTo(mThreeList) { entry ->
                SaleChartData(
                    stationId = staionId,
                    productId = productId,
                    date = entry.key,
                    quantity = entry.value.sumOf { it.quantity.intValue }.toFloat()
                )
            }

        mBinding
            .thirdSale3
            .apply {
                if (mThreeList.isEmpty()) clear()
                else {
                    mBinding
                        .thirdSaleTitle2
                        .text =
                        if (productId.isEmpty()) "全部商品"
                        else {
                            val item = mTwoList.first { it.productId == productId }
                            "${item.productName}（销量：${item.quantity.toInt()}）"
                        }

                    setSingleData(
                        entries = mThreeList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.quantity)
                        },
                        colorList = when {
                            staionId.isEmpty() -> listOf(
                                getViewModel()
                                    .brandColor()[
                                        if (productId.isEmpty()) 0
                                        else mTwoList.indexOfFirst { it.productId == productId } % 24
                                ]
                            )
                            else -> listOf(
                                getViewModel()
                                    .brandColor()[
                                        mOneList.indexOfFirst { it.stationId == staionId } % 24
                                ]
                            )
                        },
                        isHighlight = false,
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 获取所有水站商品销量
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .saleList(
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { list ->
                    mAllList.clear()
                    mAllList.addItems(list)

                    mOneList.clear()
                    mAllList
                        .groupBy { it.eid }
                        .mapTo(mOneList) { entry ->
                            SaleChartData(
                                stationId = entry.key,
                                stationName = entry.value[0].ename,
                                quantity = entry.value.sumOf { it.quantity.intValue }.toFloat()
                            )
                        }

                    setSaleFirstData()
                    setSaleSecondData(mStationId)
                    setSaleThirdData(mStationId, mProductId)
                }
            )
    }

}